FastClick.attach(document.body);

let myAudio = document.querySelector('#myAudio'),
    musicBtn = document.querySelector('.broadcast'),
    Albums = document.querySelector('.base-info .Album')
    titleBox = document.querySelector('.song-info .title'),
    authorBox = document.querySelector('.song-info .autr'),
    wrapperBox = document.querySelector('.wrapper'),
    lyricList = [];

const format = function format(num) {
    let minutes = Math.floor(num / 60),
        seconds = Math.ceil(num - minutes * 60);
    if (minutes < 10) minutes = '0' + minutes;
    if (seconds < 10) seconds = '0' + seconds;
    return `${minutes}:${seconds}`;
};
const handleTimeAndRate = function handleTimeAndRate() {
    let { currentTime, duration } = myAudio;
    if (isNaN(currentTime) || isNaN(duration)) return;
    if (currentTime >= duration) {
        currentTime = 0;
    }
};
myAudio.onloadedmetadata = handleTimeAndRate;
$sub.on('music', handleTimeAndRate);

const render = function render(lyric) {
    // 解析出标题和作者
    let title = lyric.match(/\[ti&#58;([^\]]+)\]/),
        author = lyric.match(/\[ar&#58;([^\]]+)\]/);
    if (title) titleBox.innerHTML = title[1];
    if (author) authorBox.innerHTML = author[1];

    // 解析歌词
    let arr = [];
    lyric.split('\n')
    lyric.replace(/\[(\d+):(\d+).(?:\d+)\]([^/\n]+)/g, (_, minutes, seconds, text) => {
        arr.push({
            minutes,
            seconds,
            text
        });
    });
    let str = ``;
    arr.forEach(item => {
        let { minutes, seconds, text } = item;
        str += `<p minutes="${minutes}" seconds="${seconds}">
            ${text}
        </p>`;
    });
    wrapperBox.innerHTML = str;

    // 其他操作
    musicBtn.style.display = 'block';
    lyricList = Array.from(wrapperBox.querySelectorAll('p'));
};
const queryData = function queryData() {
    return new Promise(resolve => {
        let xhr = new XMLHttpRequest;
        xhr.open('GET', './json/lyric.json');
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = JSON.parse(xhr.responseText);
                resolve(data);
            }
        };
        xhr.send();
    });
};
queryData()
    .then(value => {
        return value.lyric;
    })
    .then(lyric => {
        render(lyric);
    });


/* 控制歌词对应 */
let n = 0;
$sub.on('music', function () {
    let { currentTime, duration } = myAudio,
        [minutes, seconds] = format(currentTime).split(':'),
        H = lyricList[0].offsetHeight;
    // 从所有歌词中筛选出：和播放时间匹配的歌词集合 & 不匹配的集合
    // 一经发现匹配再处理
    let matchArr = [],
        matchNoneArr = [];
    lyricList.forEach(item => {
        let a = item.getAttribute('minutes'),
            b = item.getAttribute('seconds');
        if (a === minutes && b === seconds) {
            matchArr.push(item);
            return;
        }
        matchNoneArr.push(item);
    });
    if (matchArr.length > 0) {
        matchArr.forEach(item => item.classList.add('active'));
        matchNoneArr.forEach(item => item.classList.remove('active'));
        // 匹配的同时不要忘记：WRAPPER的挪动
        n += matchArr.length;
        if (n >= 1) {
            wrapperBox.style.transform = `translateY(${-(n - 1) * H}px)`;
        }
    }
    console.log(matchArr);
    // 播放完毕的处理
    if (currentTime >= duration) {
        myAudio.pause();
        musicBtn.classList.remove('move');
        wrapperBox.style.transform = `translateY(0)`;
        lyricList.forEach(item => item.classList.remove('active'));
        n = 0;
        if (timer) {
            clearInterval(timer);
            timer = null;
        }
    }
});
let timer = null;
musicBtn.onclick = function () {
    if (myAudio.paused) {
        // 当前是暂停的：我们让其播放
        myAudio.play();
        Albums.classList.add('move');
        musicBtn.style.opacity='0';

        if (!timer) {
            $sub.emit('music');
            timer = setInterval(() => {
                $sub.emit('music');
            }, 1000);
        }
        return;
    }
    // 当前是播放的：我们让其暂停
    myAudio.pause();
    Albums.classList.remove('move');
    musicBtn.style.opacity='1';
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
};
console.log(wrapperBox);
